import 'package:redux/redux.dart';
import '../models/ranking_user_entity.dart';
import '../models/leaderboard_comment_entity.dart';
import '../data/default_leaderboard_data.dart';

/// Redux排行榜状态
class ReduxLeaderboardState {
  final List<RankingUserEntity> rankingCollection;
  final List<LeaderboardCommentEntity> commentCollection;

  const ReduxLeaderboardState({
    this.rankingCollection = const [],
    this.commentCollection = const [],
  });

  ReduxLeaderboardState copyWith({
    List<RankingUserEntity>? rankingCollection,
    List<LeaderboardCommentEntity>? commentCollection,
  }) {
    return ReduxLeaderboardState(
      rankingCollection: rankingCollection ?? this.rankingCollection,
      commentCollection: commentCollection ?? this.commentCollection,
    );
  }
}

/// Redux排行榜动作
abstract class ReduxLeaderboardAction {}

class InitializeLeaderboardDataAction extends ReduxLeaderboardAction {
  final List<RankingUserEntity> rankingList;
  final List<LeaderboardCommentEntity> commentList;
  InitializeLeaderboardDataAction({
    required this.rankingList,
    required this.commentList,
  });
}

class UpdateUserLikeCountAction extends ReduxLeaderboardAction {
  final String userId;
  final int newLikeCount;
  UpdateUserLikeCountAction({required this.userId, required this.newLikeCount});
}

class AddLeaderboardCommentAction extends ReduxLeaderboardAction {
  final LeaderboardCommentEntity newComment;
  AddLeaderboardCommentAction(this.newComment);
}

class RemoveLeaderboardCommentAction extends ReduxLeaderboardAction {
  final String commentId;
  RemoveLeaderboardCommentAction(this.commentId);
}

class RefreshRankingsAction extends ReduxLeaderboardAction {}

/// Redux排行榜Reducer
ReduxLeaderboardState leaderboardReducer(
  ReduxLeaderboardState state,
  dynamic action,
) {
  if (action is InitializeLeaderboardDataAction) {
    return state.copyWith(
      rankingCollection: action.rankingList,
      commentCollection: action.commentList,
    );
  }

  if (action is UpdateUserLikeCountAction) {
    final updatedRankings =
        state.rankingCollection.map((ranking) {
          if (ranking.userId == action.userId) {
            return ranking.copyWith(
              totalLikeCount: action.newLikeCount,
              lastUpdateTime: DateTime.now(),
            );
          }
          return ranking;
        }).toList();

    // 重新计算排名
    updatedRankings.sort(
      (a, b) => b.totalLikeCount.compareTo(a.totalLikeCount),
    );
    final rerankedList =
        updatedRankings.asMap().entries.map((entry) {
          return entry.value.copyWith(rankPosition: entry.key + 1);
        }).toList();

    return state.copyWith(rankingCollection: rerankedList);
  }

  if (action is AddLeaderboardCommentAction) {
    final updatedComments = List<LeaderboardCommentEntity>.from(
      state.commentCollection,
    )..insert(0, action.newComment); // 新评论插入到顶部
    return state.copyWith(commentCollection: updatedComments);
  }

  if (action is RemoveLeaderboardCommentAction) {
    final updatedComments =
        state.commentCollection
            .where((comment) => comment.commentId != action.commentId)
            .toList();
    return state.copyWith(commentCollection: updatedComments);
  }

  if (action is RefreshRankingsAction) {
    // 重新计算所有排名
    final sortedRankings = List<RankingUserEntity>.from(
      state.rankingCollection,
    );
    sortedRankings.sort((a, b) => b.totalLikeCount.compareTo(a.totalLikeCount));
    final rerankedList =
        sortedRankings.asMap().entries.map((entry) {
          return entry.value.copyWith(rankPosition: entry.key + 1);
        }).toList();

    return state.copyWith(rankingCollection: rerankedList);
  }

  return state;
}

/// Redux排行榜服务
class ReduxLeaderboardManager {
  static final ReduxLeaderboardManager _instance =
      ReduxLeaderboardManager._internal();
  factory ReduxLeaderboardManager() => _instance;
  ReduxLeaderboardManager._internal();

  Store<dynamic>? _store;

  void initialize(Store<dynamic> store) {
    _store = store;
  }

  Store<dynamic> get store {
    if (_store == null) throw Exception('Leaderboard service not initialized');
    return _store!;
  }

  void initializeLeaderboardData() {
    final leaderboardData =
        DefaultLeaderboardDataCollection.defaultLeaderboardData;
    store.dispatch(
      InitializeLeaderboardDataAction(
        rankingList: leaderboardData.rankings,
        commentList: leaderboardData.comments,
      ),
    );
  }

  List<RankingUserEntity> getAllRankings() =>
      List.from(store.state.leaderboardState.rankingCollection);

  List<LeaderboardCommentEntity> getAllComments() =>
      List.from(store.state.leaderboardState.commentCollection);

  RankingUserEntity? getUserRanking(String userId) {
    try {
      return store.state.leaderboardState.rankingCollection.firstWhere(
        (ranking) => ranking.userId == userId,
      );
    } catch (e) {
      return null;
    }
  }

  int getUserRankPosition(String userId) {
    final ranking = getUserRanking(userId);
    return ranking?.rankPosition ?? 0;
  }

  int getUserTotalLikes(String userId) {
    final ranking = getUserRanking(userId);
    return ranking?.totalLikeCount ?? 0;
  }

  List<RankingUserEntity> getTopRankings(int limit) {
    final rankings = getAllRankings();
    return rankings.take(limit).toList();
  }

  Future<bool> updateUserLikeCount(String userId, int newLikeCount) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));
      store.dispatch(
        UpdateUserLikeCountAction(userId: userId, newLikeCount: newLikeCount),
      );
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> addComment(LeaderboardCommentEntity newComment) async {
    try {
      await Future.delayed(const Duration(milliseconds: 400));
      store.dispatch(AddLeaderboardCommentAction(newComment));
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> removeComment(String commentId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));
      store.dispatch(RemoveLeaderboardCommentAction(commentId));
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> refreshRankings() async {
    try {
      await Future.delayed(const Duration(milliseconds: 500));
      store.dispatch(RefreshRankingsAction());
      return true;
    } catch (e) {
      return false;
    }
  }

  int getTotalUsersCount() =>
      store.state.leaderboardState.rankingCollection.length;
  int getTotalCommentsCount() =>
      store.state.leaderboardState.commentCollection.length;

  List<LeaderboardCommentEntity> getCommentsSortedByTime() {
    final comments = List<LeaderboardCommentEntity>.from(
      store.state.leaderboardState.commentCollection,
    );
    comments.sort((a, b) => b.commentTime.compareTo(a.commentTime));
    return comments;
  }
}
